# -*- coding: UTF-8 -*-
# 2023/11/26 23:42
import os
from tkinter import filedialog

from ttkbootstrap import Toplevel, Frame, Button, Label, IntVar
from ttkbootstrap.tooltip import ToolTip

from phone.class_hot_new_search_frame import class_hot_new_search_frame
from phone.phone_tools import get_page_img
from tools.get_configer import my_configer
from tools.get_icon import last_page, skip_page, next_page, confirm, select_all, set_save_path
from tools.get_logger import get_logger
from tools.img_tool import set_pil_img
from tools.input_validation import int_placeholder_Entry
from tools.pool_download_image import pool_download_image

configer = my_configer()
loger = get_logger()


class class_page(Toplevel):
    """
    指定分类下载弹出窗口
    [
        {"img_name": f'{"_".join(img_info["tag"])}_{img_info["id"]}.jpg',
         "img_id": img_info["id"],
         "img_url":
             {
                 "thumb": img_info["thumb"],  # 预览350*540
                 "img": img_info["img"],  # 标准大小1080*1920
                 "preview": img_info["preview"]  # 最大2000*300,存在损坏的
             }
         } for img_info in response["res"]["vertical"]
    ]

    btn_img_id = getattr(btn, "btn_img_id")
    btn_img_url = getattr(btn, "btn_img_url")
    btn_name = getattr(btn, "btn_name")
    btn_cover_save_path = getattr(btn, "btn_cover_save_path")
    """

    def __init__(self, event, title, *args, **kwargs):
        """
        根据传入的btn和master生成分类图片展示窗口
        :param btn: 选择的class信息,btn本身可以通过getattr(btn, property)方式获取,class_id和class_name
        :param master: 分类下图片窗口父对象
        :param args: Toplevel参数
        :param kwargs: Toplevel参数
        """
        super().__init__(*args, **kwargs)

        self.master = event.widget
        self.title = title

        self.class_id = getattr(self.master, "class_id")
        self.class_name = getattr(self.master, "class_name")
        self.page_no = IntVar(self, 0)
        self.page_sum = 40  # 获取三倍这个数字,超出50后一页返回30

        self.Toplevel_init()
        self.setupUI()
        self.setlayout()
        self.setCallback()
        self.setBalloon()

    def Toplevel_init(self):
        self.grab_set()  # 设置为模态窗口
        # self.place_window_center()  # 居中
        self.wm_title(self.title)
        self.minsize(1250, 900)

    def setupUI(self):
        # 空间布局组件
        self.class_frame = Frame(self)
        self.download_info_frame = Frame(self.class_frame)

        # 操作按钮___________________________________________________________________________________
        # 上一页
        self.last_but_img = set_pil_img(last_page, (50, 50))
        self.last_but = Button(self.download_info_frame, text="上一页", image=self.last_but_img, compound='bottom')
        # 下一页
        self.next_but_img = set_pil_img(next_page, (50, 50))
        self.next_but = Button(self.download_info_frame, text="下一页", image=self.next_but_img, compound='bottom')

        # 指定分页
        self.skip_page_button_img = set_pil_img(skip_page, (50, 50))
        self.skip_page_button = Button(self.download_info_frame, text="跳转至", image=self.skip_page_button_img, compound='bottom')
        self.skip_page_entry = int_placeholder_Entry(self.download_info_frame, placeholder="在此填写跳转分页", textvariable=self.page_no, width=6)

        # 确认下载按钮
        self.confirm_download_button_img = set_pil_img(confirm, (50, 50))
        self.confirm_download_button = Button(self.download_info_frame, text="确认下载", image=self.confirm_download_button_img, compound='bottom')

        # 本页全下载
        self.select_all_btn_img = set_pil_img(select_all, (50, 50))
        self.select_all_btn = Button(self.download_info_frame, text="本页全部下载", image=self.select_all_btn_img, compound='bottom')

        # 保存按钮,保存label
        self.save_path = os.path.abspath('./')
        self.save_to_button_img = set_pil_img(set_save_path, (50, 50))
        self.save_to_button = Button(self.download_info_frame, text="保存至", image=self.save_to_button_img, compound='bottom')
        self.save_to_label = Label(self.download_info_frame, text=self.save_path)

        # 预览空间___________________________________________________________________________________
        self.class_page_frame = class_hot_new_search_frame(line_num=5,
                                                           name_id_tag_urls=get_page_img(self.class_id, self.page_sum, self.page_no.get()),
                                                           master=self.class_frame)

    def setlayout(self):
        # 几个主空间布局
        self.class_frame.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.download_info_frame.place(relx=0, rely=0, relwidth=1, relheight=0.1)
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        # 按钮布局
        self.last_but.pack(side="left", padx=15)
        self.next_but.pack(side="left", padx=15)
        self.skip_page_button.pack(side="left", padx=3)
        self.skip_page_entry.pack(side="left", padx=3)
        self.confirm_download_button.pack(side="left", padx=15)
        self.select_all_btn.pack(side="left", padx=15)
        self.save_to_button.pack(side="left", padx=3)
        self.save_to_label.pack(side="left", padx=3)

    def setCallback(self):
        self.save_to_button.config(command=self.get_save_to_path)
        self.next_but.config(command=self.display_next_page)
        self.last_but.config(command=self.display_last_page)
        self.skip_page_button.config(command=self.skip_specify_page)
        self.confirm_download_button.config(command=self.confirm_download_button_callback)
        self.select_all_btn.config(command=self.select_all_callback)

    def setBalloon(self):
        ToolTip(self.skip_page_entry, "设置指定跳转页码")

    def get_save_to_path(self):
        save_path = filedialog.askdirectory(initialdir="./",
                                            parent=self,
                                            title="选择保存目录")

        if save_path in ["", None]:
            loger.info(f"未选择目录,忽略")
            return
        else:
            self.save_path = save_path
            self.save_to_label.config(text=save_path)

    def display_next_page(self):
        self.page_no.set(self.page_no.get() + 1)
        next_class_page_frame = class_hot_new_search_frame(line_num=5,
                                                           name_id_tag_urls=get_page_img(self.class_id, self.page_sum, self.page_no.get()),
                                                           master=self.class_frame)

        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = next_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def display_last_page(self):
        self.page_no.set(self.page_no.get() - 1)
        last_class_page_frame = class_hot_new_search_frame(line_num=5,
                                                           name_id_tag_urls=get_page_img(self.class_id, self.page_sum, self.page_no.get()),
                                                           master=self.class_frame)

        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = last_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def skip_specify_page(self):
        specify_class_page_frame = class_hot_new_search_frame(line_num=5,
                                                              name_id_tag_urls=get_page_img(self.class_id, self.page_sum, self.page_no.get()),
                                                              master=self.class_frame)

        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = specify_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def confirm_download_button_callback(self):
        """
        确认下载回调
        """
        loger.info(f"提交按照选择下载")

        # 判断保存目录
        page_save_path = os.path.join(self.save_path, self.title)
        if not os.path.exists(page_save_path):
            os.mkdir(page_save_path)

        download_info_list = self.class_page_frame.get_select_btn()

        _all_download_info_list = list()
        for tag_id_key_urls_dict in download_info_list:
            _img_name = tag_id_key_urls_dict['img_name']  # tag里面已经有classid和图id
            _save_path = os.path.abspath(os.path.join(self.save_path, self.class_name, _img_name))
            _max_img_url = tag_id_key_urls_dict["img_urls"]["preview"]
            _all_download_info_list.append([_save_path, _max_img_url])

            loger.info(f"解析下载保存地址:{_max_img_url}, 图片url:{_save_path}")

        # 提交下载
        pool_download_image(_all_download_info_list)

    def select_all_callback(self):
        """
        全选回调
        """
        loger.info(f"提交本页全部下载")

        # 判断保存目录
        page_save_path = os.path.join(self.save_path, self.title)
        if not os.path.exists(page_save_path):
            os.mkdir(page_save_path)

        download_info_list = self.class_page_frame.get_all_btn()

        _all_download_info_list = list()
        for tag_id_key_urls_dict in download_info_list:
            _img_name = tag_id_key_urls_dict['img_name']  # tag里面已经有classid和图id
            _save_path = os.path.abspath(os.path.join(self.save_path, self.class_name, _img_name))
            _max_img_url = tag_id_key_urls_dict["img_urls"]["preview"]
            _all_download_info_list.append([_save_path, _max_img_url])

            loger.info(f"解析下载保存地址:{_max_img_url}, 图片url:{_save_path}")

        # 提交下载
        pool_download_image(_all_download_info_list)
